package com.woniuxy.meal.controller.consumer;


import com.woniuxy.meal.common.ConstantData;
import com.woniuxy.meal.common.RedisKey;
import com.woniuxy.meal.entity.DietOrder;
import com.woniuxy.meal.entity.DietOrderFood;
import com.woniuxy.meal.entity.DietOrderLog;
import com.woniuxy.meal.form.message.CheckOrderMessage;
import com.woniuxy.meal.service.DietOrderLogService;
import com.woniuxy.meal.service.DietOrderService;
import com.woniuxy.meal.util.RedisUtil;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;


//15分钟后检查用户是否支付
@Component
@RocketMQMessageListener(consumerGroup = "check",topic = "orders_check")
public class CheckOrderConsumer implements RocketMQListener<CheckOrderMessage> {

    @Autowired
    private DietOrderService dietOrderService;

    @Autowired
    private DietOrderLogService dietOrderLogService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void onMessage(CheckOrderMessage msg) {
        DietOrder dietOrder = dietOrderService.getById(msg.getOderNum());
        if (dietOrder.getState()== ConstantData.ORDER_WAITE_PAY){
            dietOrder.setState(ConstantData.ORDER_ALREADY_CANCEL);
            dietOrderService.updateById(dietOrder);
            System.out.println("开始记录取消订单日志");
            DietOrderLog orderLog = new DietOrderLog();
            orderLog.setOrderNum(msg.getOderNum());
            orderLog.setOrderState("已取消");
            orderLog.setOperReason("超时未支付");
            orderLog.setOperUser("系统");
            orderLog.setOperDate(LocalDateTime.now());
            orderLog.setOperContent("订单超时未支付，系统自动取消该订单");
            dietOrderLogService.save(orderLog);

            //修改订单中食品的销量
            List<DietOrderFood> list = msg.getList();

            for (DietOrderFood dietOrderFood : list) {
                String foodSaleKey = RedisKey.getFoodSaleKey();
                try {
                    System.out.println(dietOrderFood.getCount());
                    redisUtil.zincrby(foodSaleKey,dietOrderFood.getFoodId().toString(),dietOrderFood.getCount());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

        }

    }


}
